package com.fuego.creditsystemcommodity.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuego.creditsystemcommodity.mapper.OrganizerMapper;
import com.fuego.creditsystemcommodity.service.IOrganizerService;
import jakarta.annotation.Resource;
import org.example.dto.Result;
import org.example.entity.Organizer;
import org.example.utils.CacheClient;
import org.example.utils.SystemConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.example.utils.RedisConstants.*;


@Service
public class OrganizerServiceImpl extends ServiceImpl<OrganizerMapper, Organizer> implements IOrganizerService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        //解决缓存穿透
        //Organizer organizer = queryWithPassThrough(id);
        //互斥锁解决缓存穿透
        //Organizer organizer = queryWithMutex(id);
        //逻辑过期解决缓存穿透

        Organizer organizer =cacheClient
                .queryWithLogicalExpire(CACHE_ORGANIZER_KEY,LOCK_ORGANIZER_KEY,id, Organizer.class,this::getById,CACHE_ORGANIZER_TTL,TimeUnit.MINUTES);
        if(organizer==null)
        {
            return Result.fail("店铺不存在！");
        }
        // 返回
        return Result.ok(organizer);
    }

    @Override
    @Transactional
    public Result update(Organizer organizer) {
        Long id= organizer.getId();
        if(id==null)
        {
            return Result.fail("商铺id不能为空");
        }
        //1更新数据库
        updateById(organizer);
        String key=CACHE_ORGANIZER_KEY+organizer.getId();
        stringRedisTemplate.delete(key);
        // 2删除缓存
        return Result.ok();
    }



    @Override
    public Result queryByType(Integer typeId, Integer current) {
        //1判断是否需要根据坐标查询
            Page<Organizer> page=query()
                    .eq("type_id",typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            //返回数据
            return Result.ok(page.getRecords());

    }

    @Override
    public Result queryAllOrganizer() {
        List<Organizer> organizers = getBaseMapper().queryAllOrganizer();
        // 返回结果
        return Result.ok(organizers);
    }

//    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);


   /* public Organizer queryWithLogicalExpire(Long id){
        //从redis查询商铺缓存
        String key=CACHE_ORGANIZER_KEY+id;
        String organizerJson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if(StrUtil.isBlank(organizerJson))
        {
            // 存在，直接返回
            return  null;
        }
        //4命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(organizerJson, RedisData.class);

        Organizer organizer = JSONUtil.toBean((JSONObject) redisData.getData(), Organizer.class);
        LocalDateTime expireTime=redisData.getExpireTime();
        //5判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            // 5.1未过期，直接返回店铺信息
            return organizer;
        }

        // 5.2已过期，需要缓存重建
        // 6缓存重建
        // 6.1获取互斥锁
        String lockKey=LOCK_ORGANIZER_KEY+id;
        Boolean isLock=tryLock(lockKey);
        // 6.2判断是否获取锁成功
        if(isLock){
            // TODO 6.3成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try{
                    //重建缓存
                    this.saveOrganizer2Redis(id,20L);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unlock(lockKey);

                }
            });
        }

        // 6.4返回过期的商铺信息



        return organizer;
    }*/

//    private boolean tryLock(String key){
//        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MINUTES);
//        return BooleanUtil.isTrue(flag);
//
//    }
//
//    private void unlock(String key){
//        stringRedisTemplate.delete(key);
//    }

//    public void saveOrganizer2Redis(Long id,Long expireSeconds) throws InterruptedException {
//        //1查询店铺数据
//        Organizer organizer=getById(id);
//        Thread.sleep(200);
//        // 2封装逻辑过期时间
//        RedisData redisData=new RedisData();
//        redisData.setData(organizer);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//        // 3写入Redis
//        stringRedisTemplate.opsForValue().set(CACHE_ORGANIZER_KEY+id,JSONUtil.toJsonStr(redisData));
//    }


//    public Organizer queryWithMutex(Long id){
//        //从redis查询商铺缓存
//        String key=CACHE_ORGANIZER_KEY+id;
//        String organizerJson = stringRedisTemplate.opsForValue().get(key);
//        //判断是否存在
//        if(StrUtil.isNotBlank(organizerJson))
//        {
//            // 存在，直接返回
//            Organizer organizer = JSONUtil.toBean(organizerJson, Organizer.class);
//            return  organizer;
//        }
//        //判断命中的是否是空值
//        if(organizerJson!=null)
//        {
//            // return Result.fail("店铺信息不存在");
//            return null;
//        }
//        //4实现缓存重建
//        //4.1获取互斥锁
//        String lockKey="lock:organizer"+id;
//        Organizer organizer = null;
//        try {
//            boolean isLock = tryLock(lockKey);
//            //4.2判断是否获取成功
//            if(!isLock){
//                // 4.3失败，则休眠并重试
//                Thread.sleep(50);
//                return queryWithMutex(id);
//            }
//
//            // 4.4成功，根据id查询数据库
//            organizer = getById(id);
//            //模拟重建的延时
//            Thread.sleep(200);
//            // 5不存在，返回错误
//            if(organizer==null)
//            {
//                //将空值写入redis
//                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//
//                //return Result.fail("店铺不存在！");
//                return null;
//            }
//            // 6存在，写入redis
//            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(organizer),CACHE_ORGANIZER_TTL, TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }finally {
//            //7释放互斥锁
//            unlock(lockKey);
//        }
//        // 8返回
//        //return Result.ok(organizer);
//        return organizer;
//    }
//        public Organizer queryWithPassThrough(Long id){
//            //从redis查询商铺缓存
//            String key=CACHE_ORGANIZER_KEY+id;
//            String organizerJson = stringRedisTemplate.opsForValue().get(key);
//            //判断是否存在
//            if(StrUtil.isNotBlank(organizerJson))
//            {
//                // 存在，直接返回
//                Organizer organizer = JSONUtil.toBean(organizerJson, Organizer.class);
//                return  organizer;
//            }
//            //判断命中的是否是空值
//            if(organizerJson!=null)
//            {
//                //返回一个错误信息
//               // return Result.fail("店铺信息不存在");
//                return null;
//            }
//            // 不存在，根据id查询数据库
//            Organizer organizer = getById(id);
//            // 不存在，返回错误
//            if(organizer==null)
//            {
//                //将空值写入redis
//                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//
//                //return Result.fail("店铺不存在！");
//                return null;
//            }
//            // 存在，写入redis
//            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(organizer),CACHE_ORGANIZER_TTL, TimeUnit.MINUTES);
//            // 返回
//            //return Result.ok(organizer);
//            return organizer;
//        }



}
